﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using PurchaseOrderExtra;
using System.Threading.Tasks;

namespace PresentationLayer
{
    public partial class ApprovePurchaseOrder : System.Web.UI.Page
    {
        ApprovePurchaseOrderControl control;
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Check if user exists and has permission to view this page
                if (Session["UserLoggedIn"] != null)
                {
                    List<string> list = Session["UserLoggedIn"] as List<string>;
                    if (list[0].Equals("validuser"))
                    {
                        int roleId = Convert.ToInt32(list[6]);
                        if (roleId < 6 || roleId > 7)
                        {
                            Response.Redirect("/AccessDenied.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("/Login.aspx");
                }
                #endregion

                control = new ApprovePurchaseOrderControl();

                List<string> userList = Session["UserLoggedIn"] as List<string>;
                string username = userList[3];
                user = control.GetUserByUsername(username);

                // Block the buttons to prevent multiple clicks by the user
                btnApprove.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnApprove).ToString() + ";");
                btnReject.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnReject).ToString() + ";");

                if (!IsPostBack)
                {
                    GenerateGridViewAndInfo();
                }
            }
            catch (Exception ex)
            {
                // Release block button
                btnApprove.Enabled = true;
                btnReject.Enabled = true;
            }
        }

        private void GenerateGridViewAndInfo()
        {
            string poIdString = Session["PODetail"] as string;
            if (poIdString != null)
            {
                int poId = Convert.ToInt32(poIdString);

                PurchaseOrder po = control.GetPurchaseOrderByPOId(poId);
                lblSupplierName.Text = po.Supplier.SupplierName;
                lblAttn.Text = po.Employee.EmployeeName;
                lblExpectedDate.Text = po.ExpectedDeliveryDate.Value.ToShortDateString();

                List<PurchaseOrderDisplay> list = new List<PurchaseOrderDisplay>();
                list = control.GetPurchaseOrderDisplay(poId);

                decimal total = 0;
                foreach (PurchaseOrderDisplay poDisplay in list)
                {
                    total = total + poDisplay.Amount;
                }

                gvPurchaseOrder.DataSource = list;
                gvPurchaseOrder.DataBind();

                lblTotal.Text = "Total: S$" + total;
            }
            else
            {
                lblAttn.Text = "";
                lblAttnLabel.Text = "";
                lblExpectedDate.Text = "";
                lblExpectedDateLabel.Text = "";
                lblSupplierName.Text = "";
                lblSupplierNameLabel.Text = "";
                lblTotal.Text = "";
                lblReason.Text = "";
                txtReason.Visible = false;
                btnApprove.Visible = false;
                btnReject.Visible = false;

                lblMessage.Text = "No purchase order has been selected";
            }
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            string reason = "";
            string poIdString = "";

            try
            {     
                reason = txtReason.Text;
                poIdString = Session["PODetail"] as string;
                if (poIdString != null)
                {
                    // Update to PO table
                    int poId = Convert.ToInt32(poIdString);
                    control.UpdateApprovePurchaseOrder(user, poId, reason);

                    // Save Result to HttpSession
                    string result = "Approved";
                    Session["POResult"] = result;
                }

                // Release blocked buttons
                btnApprove.Enabled = true;
                btnReject.Enabled = true;

                // Redirect to result page
                string redirect = control.RedirectToPurchaseOrderConfirmation();
                Response.Redirect(redirect);
            }
            catch (Exception ex)
            {
                // Release blocked buttons
                btnApprove.Enabled = true;
                btnReject.Enabled = true;
            }
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            string reason = "";
            string poIdString = "";

            try
            {
                reason = txtReason.Text;
                poIdString = Session["PODetail"] as string;
                if (poIdString != null)
                {
                    // Update to PO table
                    int poId = Convert.ToInt32(poIdString);
                    control.UpdateRejectPurchaseOrder(user, poId, reason);

                    // Save Result to HttpSession
                    string result = "Rejected";
                    Session["POResult"] = result;
                }

                // Release blocked buttons
                btnApprove.Enabled = true;
                btnReject.Enabled = true;

                // redirect to result page
                string redirect = control.RedirectToPurchaseOrderConfirmation();
                Response.Redirect(redirect);
            }
            catch (Exception ex)
            {
                // Release blocked buttons
                btnApprove.Enabled = true;
                btnReject.Enabled = true;
            }
        }

        protected void btnReturnToList_Click(object sender, EventArgs e)
        {
            try
            {
                Session.Remove("POResult");
                string redirectURL = control.RedirectToPurchaseOrderListForApproval();
                Response.Redirect(redirectURL);
            }
            catch (Exception ex)
            {
            }
        }

    }
}